package com.mdata.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mdata.common.DefinitionException;
import com.mdata.common.ResponseEnum;
import com.mdata.mapper.UserDao;
import com.mdata.model.po.SubjectUser;
import com.mdata.model.po.User;
import com.tencent.wework.Finance;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        return new SimpleAuthorizationInfo();
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("认证");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        User user = userDao.selectOne(new QueryWrapper<User>().lambda().eq(User::getUserName, userToken.getUsername()));
        if(Objects.isNull(user)){
            // UnknownAccountException
            return null;
        }

        // TODO 从数据库读取用户的绑定的微信信息
        SubjectUser subjectUser = SubjectUser.builder()
                .id(user.getId())
                .wechatCorpId("ww689e7f7396dd4ba7")
                .wechatCustomerContactSecret("QvK7PGdiFkc5vCzqzuo9BpoD1j-dIVj7dEegMYbTXXA")
                .wechatAddressBookSecret("755jGYXZVDwNSnW6IvcHDOjExa-Uw7Zm-0h2syxFTFE")
                .wechatManageSecret("x8ss5QoMBb45q3IKUfbuEvM3Kwzagcf0sR9rvaVGNDY")
                .wechatSessionArchivingSecret("")
                .build();

//        long sdk = Finance.NewSdk();
//        long ret = Finance.Init(sdk, subjectUser.getWechatCorpId(), subjectUser.getWechatSessionArchivingSecret());
//        if(ret != 0){
//            Finance.DestroySdk(sdk);
//            log.error("init sdk err ret " + ret);
//            throw new DefinitionException(ResponseEnum.SESSION_ARCHIVING_INIT_ERROR);
//        }
//        subjectUser.setFinanceSdk(sdk);

        // 此处放user两个作用：1、doGetAuthorizationInfo授权方法可以取到当前登录的user 2、redis做缓存是需要key 获取id做key.
        return new SimpleAuthenticationInfo(subjectUser, user.getPassword(), "");
    }
}
